<?php
header('content-type: application/json; charset=utf-8');
if(array_key_exists('json',$_GET)){
	require 'jsonwrapper.php';
	if(array_key_exists('add',$_GET)){
		if(!block_exists($_GET['ki'],$_GET['kit'])){
			insert_block($_GET['ki'],$_GET['kit']);
		}
		$data = list_blocked($_GET['ki']);
		echo $_GET['callback'] . '('.json_encode($data).')';
	}
	else if(array_key_exists('getblock',$_GET)){
		$data = list_blocked($_GET['getblock']);
		echo $_GET['callback'] . '('.json_encode($data).')';
	}
	else if(array_key_exists('remove',$_GET)){
		$ki=$_GET['ki'];
		$kit=$_GET['kit'];
		$uri = "names.txt";
		$blockFile = fopen($uri, 'r') or die('szar rizzsel');
		$content='';
		$needtowrite=false;
		while(!feof($blockFile))
		{
			$line=fgets($blockFile);
			$nevek=explode(';',$line);
			if($nevek[0] != $ki || $nevek[1] != ($kit."\n"))
				$content.=$line;
			else
				$needtowrite=true;
		}
		fclose($blockFile);
		//write the new content
		if($needtowrite){
			$blockFile = fopen($uri, 'w') or die('szar rizzsel');
			fwrite($blockFile, $content);
			fclose($blockFile);
		}
		$data = list_blocked($_GET['ki']);
		echo $_GET['callback'] . '('.json_encode($data).')';
	}
}
function list_blocked($ki){
	$uri = "names.txt";
	$blockFile = fopen($uri, 'r') or die('szar rizzsel');
	$names=array();
	while(!feof($blockFile))
	{
		$line=fgets($blockFile);
		$nevek=explode(';',$line);
		if($nevek[0] == $ki){
			$name=explode("\n",$nevek[1]);
			$names[]=$name[0];
		}
	}
	fclose($blockFile);
	return $names;
}
function block_exists($ki,$kit){
	$uri = "names.txt";
	$blockFile = fopen($uri, 'r') or die('szar rizzsel');
	$exists = false;
	while(!feof($blockFile))
	{
		$line=fgets($blockFile);
		$nevek=explode(';',$line);
		if($nevek[0] == $ki && $nevek[1] == ($kit."\n"))
			$exists = true;
	}
	fclose($blockFile);
	return $exists;
}
function insert_block($ki,$kit){
	$uri = "names.txt";
	$blockFile = fopen($uri, 'a') or die('szar rizzsel');
	$blockData = "$ki;$kit\n";
	fwrite($blockFile, $blockData);
	fclose($blockFile);
}
if(array_key_exists('lista',$_GET)){
	$uri = "names.txt";
	$blockFile = fopen($uri, 'r') or die('szar rizzsel');
	while(!feof($blockFile))
	{
		$line=fgets($blockFile);
		echo $line;
	}
	fclose($blockFile);
}
?>